﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.Extensions.Logging;


namespace WMS.Extensions
{

    public class MinioSetupService
    {
        private readonly IAmazonS3 _s3Client;
        private readonly ILogger<MinioSetupService> _logger;

        public MinioSetupService(IAmazonS3 s3Client, ILogger<MinioSetupService> logger)
        {
            _s3Client = s3Client;
            _logger = logger;
        }

        /// <summary>
        /// 设置桶为公开访问
        /// </summary>
        public async Task<bool> SetBucketPublicAsync(string bucketName)
        {
            try
            {
                var policy = $@"{{
                ""Version"": ""2012-10-17"",
                ""Statement"": [
                    {{
                        ""Effect"": ""Allow"",
                        ""Principal"": ""*"",
                        ""Action"": ""s3:GetObject"",
                        ""Resource"": ""arn:aws:s3:::{bucketName}/*""
                    }}
                ]
            }}";

                var request = new PutBucketPolicyRequest
                {
                    BucketName = bucketName,
                    Policy = policy
                };

                await _s3Client.PutBucketPolicyAsync(request);
                _logger.LogInformation($"桶 {bucketName} 已设置为公开访问");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"设置桶公开访问失败: {bucketName}");
                return false;
            }
        }
    }
}
